<template>
  <el-card class="container-card">
    <el-form label-width="80px" :rules="rules" :model="spu" ref="form">
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="请选择SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>

      <el-form-item label="SPU品牌" prop="tmId">
        <el-select placeholder="请选择SKU品牌" v-model="spu.tmId">
          <el-option
            v-for="tm in tmList"
            :label="tm.tmName"
            :value="tm.id"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          rows="2"
          placeholder="请输入SPU描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          :action="`${baseAPI}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          accept="image/jpeg,image/png,image/jpg"
          :class="{ 'spu-img-upload': this.spu.spuImageList.length > 2 }"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
        <el-dialog :visible.sync="img.dialogVisible" width="40%">
          <img width="100%" :src="img.dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          :placeholder="`还剩${saleAttrList.length}个销售属性`"
          v-model="baseSaleAttr"
        >
          <el-option
            v-for="sa in saleAttrList"
            :label="sa.name"
            :value="`${sa.id}:${sa.name}`"
            :key="sa.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          :disabled="!baseSaleAttr"
          icon="el-icon-plus"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table :data="spu.spuSaleAttrList" border class="container-table">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="属性名" width="100" prop="saleAttrName" />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-tag
                :key="index"
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                closable
                class="attr-value-tag"
                @close="delAttrValue(row.spuSaleAttrValueList, index)"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                v-show="row.isEdit"
                :ref="$index"
                class="attr-value-input"
                size="small"
                v-model="saleAttrValueName"
                @keyup.enter.native="$event.target.blur"
                @blur="setAttrValue(row)"
              >
              </el-input>
              <el-button
                v-show="!row.isEdit"
                class="button-new-tag"
                size="small"
                @click="showEditAttr(row, $index)"
                >+ 添加属性值</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除吗？"
                @onConfirm="delAttr(row, $index)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqAllTrademark } from '@/api/product/trademark'
import { reqSaleAttrList, reqsaveSpuInfo } from '@/api/product/spu'
import { mapState } from 'vuex'
export default {
  name: 'AddSpu',
  async mounted() {
    const [trademarkRes, SaleAttrRes] = await Promise.allSettled([
      reqAllTrademark(),
      reqSaleAttrList()
    ])
    if (trademarkRes.status === 'fulfilled') {
      this.tmList = trademarkRes.value
    } else {
      this.$message.error('无法获取匹配数据')
    }
    if (SaleAttrRes.status === 'fulfilled') {
      this.saleAttrList = SaleAttrRes.value
    } else {
      this.$message.error('无法获取销售属性数据')
    }
  },
  data() {
    const validator = (rule, value, callback) => {
      if (!this.spu.spuSaleAttrList.length) {
        callback('请至少添加一个销售属性')
      }
      const hasSaleAttrValueList = this.spu.spuSaleAttrList.every(
        spuSaleAttr => spuSaleAttr.spuSaleAttrValueList.length
      )
      if (!hasSaleAttrValueList) {
        callback('每个销售属性至少要有一个属性值')
      }
      callback()
    }
    return {
      spu: {
        spuName: '',
        tmId: '',
        description: '',
        spuImageList: [],
        spuSaleAttrList: []
      },
      tmList: [],
      saleAttrList: [],
      baseSaleAttr: '',
      saleAttrValueName: '',
      img: {
        dialogImageUrl: '',
        dialogVisible: false
      },
      baseAPI: process.env.VUE_APP_BASE_API,
      rules: {
        spuName: [
          { required: true, message: '请输入SPU名称', trigger: 'blur' }
        ],
        tmId: [
          { required: true, message: '请选择品牌名称', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入SPU描述', trigger: 'blur' }
        ],
        spuImageList: [{ required: true, message: '请上传图片' }],
        spuSaleAttrList: [
          {
            required: true,
            trigger: 'blur',
            validator
          }
        ]
      }
    }
  },
  computed: {
    ...mapState('category', ['category3Id'])
  },
  methods: {
    handleRemove(file) {
      this.spu.spuImageList = this.spu.spuImageList.filter(
        spuImage => spuImage.imgUrl !== file.response.data
      )
    },
    handlePictureCardPreview(file) {
      this.img.dialogImageUrl = file.url
      this.img.dialogVisible = true
    },
    handleAvatarSuccess(res, file) {
      this.spu.spuImageList.push({
        imgName: file.name,
        imgUrl: res.data
      })
      this.$refs.form.clearValidate(['spuImageList'])
    },
    beforeAvatarUpload(file) {
      const fileType = ['image/jpeg', 'image/png', 'image/jpg']
      const isValidateType = fileType.indexOf(file.type) > -1

      const isValidateSize = file.size / 1024 < 500

      if (!isValidateType) {
        this.$message.error('上传品牌图片只能是 JPG 或 PNG 格式!')
      }
      if (!isValidateSize) {
        this.$message.error('上传品牌图片大小不能超过 500KB!')
      }
      return isValidateType && isValidateSize
    },
    addAttr() {
      const [baseSaleAttrId, saleAttrName] = this.baseSaleAttr.split(':')
      this.spu.spuSaleAttrList.push({
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
      })
      this.saleAttrList = this.saleAttrList.filter(
        saleAttr => saleAttr.id !== +baseSaleAttrId
      )
      this.baseSaleAttr = ''
    },
    delAttr(attr, index) {
      this.spu.spuSaleAttrList.splice(index, 1)
      this.saleAttrList.push({
        id: attr.baseSaleAttrId,
        name: attr.saleAttrName
      })
      this.saleAttrList.sort((a, b) => a.id - b.id)
    },
    showEditAttr(row, index) {
      this.$set(row, 'isEdit', true)
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    setAttrValue(row) {
      const { saleAttrValueName } = this
      if (saleAttrValueName.trim()) {
        row.spuSaleAttrValueList.push({
          saleAttrValueName,
          baseSaleAttrId: row.baseSaleAttrId,
          saleAttrName: row.saleAttrName
        })
        this.saleAttrValueName = ''
      }
      row.isEdit = false
    },
    delAttrValue(spuSaleAttrValueList, index) {
      spuSaleAttrValueList.splice(index, 1)
    },
    cancel() {
      this.$emit('updateShow', 1)
    },
    saveSpu() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          //校验成功发送请求保存数据
          const { category3Id, spu } = this
          const {
            spuImageList,
            spuSaleAttrList,
            description,
            spuName,
            tmId
          } = spu
          await reqsaveSpuInfo({
            category3Id,
            description,
            spuName,
            tmId,
            spuImageList,
            spuSaleAttrList
          })
          this.cancel()
        }
      })
    }
  }
}
</script>

<style scoped>
.attr-value-input {
  width: 105px;
}
.attr-value-tag {
  margin-right: 10px;
}
</style>
